package com.example.ldachu.testdownload.http.util;

import com.example.ldachu.testdownload.http.base.BaseRequest;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author zxKueen on 2017-12-22 14:21
 *         Email: 4994766@qq.com
 */

public class SortMapUtil {
    //将map通过key进行排序
    public static String getChkValue2(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> resultMap = sortMapByKey(map);    //按Key进行排序

        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            sb.append(entry.getValue());
        }
        sb.append(BaseRequest.KEY2);

        return sb.toString();
    }

    /**
     * 使用 Map按key进行排序，按升序
     *
     * @param map
     * @return
     */
    private static Map<String, String> sortMapByKey(Map<String, String> map) {

        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<>(
                new MapKeyComparator());


        sortMap.putAll(map);

        return sortMap;
    }

    public static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {
            return str1.toLowerCase().compareTo(str2.toLowerCase());
        }
    }
}
